const { DataTypes } = require('sequelize');
const { sequelize } = require('../config/database');

const FailedTokenOperation = sequelize.define('FailedTokenOperation', {
  id: {
    type: DataTypes.BIGINT,
    autoIncrement: true,
    primaryKey: true,
    comment: '自增主键',
  },
  reserve_id: {
    type: DataTypes.STRING(255),
    allowNull: false,
    comment: '预留ID，与外部系统对应',
  },
  operation_type: {
    type: DataTypes.ENUM('confirm', 'cancel'),
    allowNull: false,
    comment: '操作类型：confirm=确认扣费，cancel=取消扣费',
  },
  error_message: {
    type: DataTypes.TEXT,
    allowNull: false,
    comment: '失败错误信息',
  },
  status_code: {
    type: DataTypes.INTEGER,
    allowNull: true,
    comment: 'HTTP响应状态码',
  },
  retry_count: {
    type: DataTypes.INTEGER,
    allowNull: false,
    defaultValue: 0,
    comment: '已重试次数',
  },
  max_retries: {
    type: DataTypes.INTEGER,
    allowNull: false,
    defaultValue: 5,
    comment: '最大重试次数',
  },
  status: {
    type: DataTypes.ENUM('pending', 'retrying', 'succeeded', 'failed', 'abandoned'),
    allowNull: false,
    defaultValue: 'pending',
    comment: '处理状态',
  },
  created_at: {
    type: DataTypes.DATE,
    allowNull: false,
    defaultValue: DataTypes.NOW,
    comment: '首次失败时间',
  },
  updated_at: {
    type: DataTypes.DATE,
    allowNull: false,
    defaultValue: DataTypes.NOW,
    comment: '最后更新时间',
  },
  next_retry_at: {
    type: DataTypes.DATE,
    allowNull: true,
    comment: '下次重试时间',
  },
  succeeded_at: {
    type: DataTypes.DATE,
    allowNull: true,
    comment: '成功处理时间',
  },
  abandoned_at: {
    type: DataTypes.DATE,
    allowNull: true,
    comment: '放弃处理时间',
  },
  last_error: {
    type: DataTypes.TEXT,
    allowNull: true,
    comment: '最后一次错误信息',
  },
}, {
  tableName: 'failed_token_operations',
  comment: '失败的token操作记录表',
  timestamps: false, // 手动管理 created_at/updated_at
  indexes: [
    {
      unique: true,
      name: 'uk_reserve_id_operation',
      fields: ['reserve_id', 'operation_type'],
    },
    {
      name: 'idx_status_next_retry',
      fields: ['status', 'next_retry_at'],
    },
    {
      name: 'idx_created_at',
      fields: ['created_at'],
    },
    {
      name: 'idx_operation_type',
      fields: ['operation_type'],
    },
  ],
});

module.exports = FailedTokenOperation;
